package com.lazycat.backend.service.impl.account;

import com.lazycat.backend.mapper.UserMapper;
import com.lazycat.backend.pojo.User;
import com.lazycat.backend.service.account.UserLoginService;
import com.lazycat.backend.service.impl.UserDetailsImpl;
import com.lazycat.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

//登陆服务实现类
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public Map<String, Object> login(String username, String password) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken); //如果登陆失败，会自动处理
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();

        User user = loginUser.getUser();
        String jwt = JwtUtil.createJWT(user.getId().toString());

        Map<String,Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("img", user.getImg());
        map.put("error_message", "success");
        map.put("token", jwt);
        map.put("img", Base64.getEncoder().encodeToString(user.getImg()));
        return map;
    }
}
